#include "TrajLoader.h"
#include <string.h>
#include <fstream>
#include <iostream>
#include <algorithm>

void TrajLoader_xtc::
clear ()
{
  if (inited){
    free (xx);
    xdrfile_close (xd);
    inited = false;
  }
}


TrajLoader_xtc::
TrajLoader_xtc ()
    : inited (false)
{
}

TrajLoader_xtc::
~TrajLoader_xtc ()
{
  clear ();
}

TrajLoader_xtc::
TrajLoader_xtc (const char * filename)
    : inited (false)
{
  reinit (filename);
}  

void TrajLoader_xtc::
reinit (const char * filename)
{
  char tmpname[2048];
  strncpy (tmpname, filename, 2047);
  
  xd = xdrfile_open (filename, "r");
  if (xd == NULL){
    std::cerr << "cannot open file " << filename << std::endl;
    return ;
  }
  read_xtc_natoms (tmpname, &natoms);
  step = 0;
  time = 0.;
  box.resize(3, 0.0);
  xx = (rvec *) malloc (sizeof(rvec) * natoms);
  prec = 1000.;

  inited = true;

  load ();

  xdrfile_close (xd);
  xd = xdrfile_open (filename, "r");  
  if (xd == NULL){
    std::cerr << "cannot open file " << filename << std::endl;
    return ;
  }
}

bool TrajLoader_xtc::
load ()
{
  if (inited){
    matrix tmpBox;
    int st = read_xtc (xd, natoms, &step, &time, tmpBox, xx, &prec);
    box[0] = tmpBox[0][0];
    box[1] = tmpBox[1][1];
    box[2] = tmpBox[2][2];
    if (st == exdrOK) return true;
    else return false;
  }
  else {
    return false;
  }
}

void TrajLoader_xtc::
formCoords (std::vector<std::vector<double > > & c2)
{
  c2.resize(2);

  for (unsigned ii = 0; ii < 2; ++ii){
    c2[ii].resize(3);
    for (unsigned dd = 0; dd < 3; ++dd){
      c2[ii][dd] = xx[ii][dd];
    }
  }
}


